/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Gui;

import Logica.controladores.ControladorCuotas;
import Logica.controladores.ControladorUsuario;
import Logica.cuenta.DataCuota;
import Logica.usuario.Usuario;
import Utilidades.Tablas;
import java.awt.Label;
import java.awt.TextField;
import java.awt.print.PrinterException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author manuel
 */
public class ListaUsuario extends javax.swing.JDialog {

    /**
     * Creates new form ModificarUsuario
     */
    public ListaUsuario(java.awt.Frame parent, boolean modal, int tipo) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        this.pack();
        this.setResizable(false);
        t = tipo;
        
    }
    int t;
    ControladorCuotas cc = ControladorCuotas.getInstance();
    ControladorUsuario cu = ControladorUsuario.getInstance();
    DefaultTableModel modelo;
    List<Usuario> li = new ArrayList<>();
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton2 = new javax.swing.JButton();
        l1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        box1 = new javax.swing.JComboBox();
        txt1 = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        l1.setText("Ingresar Nombre:");

        jLabel3.setText("Buscar por:");

        box1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Código", "Nombre", "Apellido", "Dirección" }));
        box1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                box1ActionPerformed(evt);
            }
        });

        txt1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt1ActionPerformed(evt);
            }
        });
        txt1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txt1KeyReleased(evt);
            }
        });

        jLabel4.setText("Clientes:");

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabla);

        jButton1.setText("Imprimir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(l1)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(box1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(txt1)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel4)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 400, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton1))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(7, 7, 7)
                                .addComponent(jLabel1)))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(box1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(l1))
                .addGap(18, 18, 18)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(37, 37, 37)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addGap(0, 8, Short.MAX_VALUE))
        );

        setSize(new java.awt.Dimension(436, 308));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2ActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        // TODO add your handling code here:
        
        l1.setText("Ingresar Código:");
        if (t==0){
            this.setTitle("Modificar un abonado");
            this.jLabel1.setText("Para modificar un abonado seleccionelo en la tabla.");
            li = cu.getListausr();
            tabla.setModel(Tablas.tablaModificarUsr(li));
        }   
        if(t==1){
            this.setTitle("Eliminar un abonado");
            this.jLabel1.setText("Para eliminar un abonado seleccionelo en la tabla.");
            li = cu.getListausr();
            tabla.setModel(Tablas.tablaModificarUsr(li));
        } 
        if(t==2){
            this.setTitle("Ver información de un abonado");
            this.jLabel1.setText("Para ver información de un abonado seleccionelo en la tabla.");
            li = cu.getListausr();
            tabla.setModel(Tablas.tablaModificarUsr(li));
        }
        if(t==3){
            this.setTitle("Agregar pago mensual");
            this.jLabel1.setText("Para agregar un pago seleccione un cliente de la tabla");
            li = cu.getListausr();
            tabla.setModel(Tablas.tablaModificarUsr(li));
        }
        if(t==4){
            this.setTitle("Listado de informacion de abonados");
            this.box1.setVisible(false);
            this.jLabel3.setVisible(false);
            this.txt1.setVisible(false);
            this.jLabel1.setText("");
            this.l1.setVisible(false);
            this.jLabel4.setText("Informcaion de abonados:");
            li = cc.getTotalCuotasImpagas();
            tabla.setModel(Tablas.DatosCliente(li));
           
        }
             
    }//GEN-LAST:event_formWindowOpened

    private void box1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_box1ActionPerformed
        // TODO add your handling code here:
        if(box1.getSelectedItem()=="Nombre"){
            l1.setText("Ingresar Nombre:");
           }
         if(box1.getSelectedItem()=="Apellido"){
            l1.setText("Ingresar Apellido:");
           }
          if(box1.getSelectedItem()=="Cedula"){
            l1.setText("Ingresar Cedula:");
           }
            if(box1.getSelectedItem()=="Código"){
            l1.setText("Ingresar Código:");
           }
            if(box1.getSelectedItem()=="Dirección"){
            l1.setText("Ingresar Dirección:");
           }
         
         
         
    }//GEN-LAST:event_box1ActionPerformed

    private void txt1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txt1ActionPerformed

    private void txt1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt1KeyReleased
        // TODO add your handling code here:
        if(box1.getSelectedItem()=="Código"){
            modelo = (DefaultTableModel) tabla.getModel();
            TableRowSorter sorter = new TableRowSorter(modelo);
            sorter.setRowFilter(RowFilter.regexFilter(txt1.getText(),0,0));
            tabla.setRowSorter(sorter);
            
        }
        if(box1.getSelectedItem()=="Nombre"){
            modelo = (DefaultTableModel) tabla.getModel();
            TableRowSorter sorter = new TableRowSorter(modelo);
            sorter.setRowFilter(RowFilter.regexFilter(txt1.getText(),0,1));
            tabla.setRowSorter(sorter);
            
        }
        if(box1.getSelectedItem()=="Apellido"){
            modelo = (DefaultTableModel) tabla.getModel();
            TableRowSorter sorter = new TableRowSorter(modelo);
            sorter.setRowFilter(RowFilter.regexFilter(txt1.getText(),0,2));
            tabla.setRowSorter(sorter);
            
        }
        if(box1.getSelectedItem()=="Dirección"){
            modelo = (DefaultTableModel) tabla.getModel();
            TableRowSorter sorter = new TableRowSorter(modelo);
            sorter.setRowFilter(RowFilter.regexFilter(txt1.getText(),0,3));
            tabla.setRowSorter(sorter);
            
        }
    }//GEN-LAST:event_txt1KeyReleased

    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaMouseClicked
// TODO add your handling code here:
        int fila = tabla.getSelectedRow();
        if (fila != -1){
            String apellido = tabla.getValueAt(fila,2).toString();
            String nombre = tabla.getValueAt(fila,1).toString();  
            int codigo = Integer.parseInt(tabla.getValueAt(fila,0).toString());            
            if (t == 0){
                ModificarUsuario mod2 = new ModificarUsuario(this, true, codigo);
                mod2.setVisible(true);        
                this.dispose();
            }
            if (t == 1){
                if(JOptionPane.showConfirmDialog(this, "Esta seguro que quiere eliminar al usuario "+nombre+" "+apellido, "Advertencia", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){
                    if(cu.EliminarUsuario(codigo)==true){
                        JOptionPane.showMessageDialog(this, "Usuario "+nombre+" "+apellido+" eliminado con éxito", "¡Éxito!", JOptionPane.INFORMATION_MESSAGE);        
                        this.dispose();
                    }
                    else{
                        JOptionPane.showMessageDialog(this, "Algo salió mal, intente nuevamante o comuniquse con Tecnopay", "Atención!", JOptionPane.INFORMATION_MESSAGE);
                    } 
                }
            } 
            if(t == 3){
                int campo = tabla.getSelectedRow();
                int cod = Integer.parseInt(tabla.getValueAt(campo,0).toString());
                ControlCuotas cc = new ControlCuotas(this,true,cod);
                cc.setVisible(true);
                this.dispose();
            }            
            if (t == 2){
                VerAbonado mod2 = new VerAbonado(this, true, codigo);
                mod2.setVisible(true);        
                this.dispose();
            }
        } 
    }//GEN-LAST:event_tablaMouseClicked

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        try {
            // TODO add your handling code here:
            this.tabla.print();
        } catch (PrinterException ex) {
            Logger.getLogger(ListaUsuario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ListaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ListaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ListaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ListaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                ListaUsuario dialog = new ListaUsuario(new javax.swing.JFrame(), true, 0);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox box1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel l1;
    private javax.swing.JTable tabla;
    private javax.swing.JTextField txt1;
    // End of variables declaration//GEN-END:variables
}
